<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use OSS\OssClient;
use Base64Url\Base64Url;

class TestController extends Controller
{
    private $accessKeyId;
    
    private $accessKeySecret;
    
    private $endpoint;
    
    private $bucketName = 'phptutorial-cn-video';
    
    private static $positions = [
        "nw" => '左上',
        "north" => '上',
        "ne" => '右上',
        "east" => '右',
        "se" => '右下',
        "south" => '下',
        "sw" => '左下',
        "west" => '左',
        "center" => '居中',
        "fill" => '铺满',
    ];
    
    public function __construct()
    {
        $this->accessKeyId = config('oss.access_key_id');
        $this->accessKeySecret = config('oss.access_key_secret');
        $this->endpoint = config('oss.endpoint');
    }
    
    public function image()
    {
        return view('image', ['positions' => self::$positions]);
    }
    
    public function upload(Request $request)
    {
        $params = $request->all();
        $originalImage = $request->file('original_image');
        if (empty($originalImage))
        {
            return back()->with("warning", "缺少待打水印目标图片")->withInput();
        }
        if (empty($params['text_mask']) && empty($params['image_mask']))
        {
            return back()->with("danger", "文字水印或图片水印至少选一项")->withInput();
        }
//         dd($params);
//         dd($originalImage->getClientOriginalExtension());
        try
        {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $ext = $originalImage->getClientOriginalExtension();
            //先保存本地一份
            $savePath = "image/oss";
            $saveResult = \Storage::putFile($savePath, $originalImage);
            $object = pathinfo($saveResult, PATHINFO_BASENAME);
            $result = $ossClient->uploadFile($this->bucketName, $object, storage_path("app/$saveResult"));
//             dd($saveResult, $result);
            //生成访问URL，有效期10分钟
            $signedUrl = $ossClient->signUrl($this->bucketName, $object, 10 * 60);
//             dd($signedUrl);
            //文字水印
            $options = [];
            $process = [];
            if (!empty($params['text_mask']))
            {
                $text = !empty($params['text']) ? $params['text'] : 'xxx工作室';
                $text = Base64Url::encode($text);
                $rotate = !empty($params['text_rotate']) ? $params['text_rotate'] : 0;
                $position = !empty($params['text_position']) && $params['text_position'] !== 'fill' ? $params['text_position'] : 'se';
                $fill = $params['text_position'] == 'fill' ? 1 : 0;
                $process[] = "watermark,type_d3F5LXplbmhlaQ==,text_{$text},color_FF3366,g_{$position},t_60,rotate_{$rotate},fill_{$fill}";
            }
            if (!empty($params['image_mask']))
            {
                $text = $request->file('image');
                if (!empty($text))
                {
                    $saveResult = \Storage::putFile($savePath, $text);
                    $maskObject = pathinfo($saveResult, PATHINFO_BASENAME);
                    $maskResult = $ossClient->uploadFile($this->bucketName, $maskObject, storage_path("app/$saveResult"));
                    $text = $maskObject;
                }
                else
                {
                    $text = '6719ad73gw1euysetc8e9j20c80erwfy.jpg';
                }
                $text = Base64Url::encode("{$text}?x-oss-process=image/resize,P_20");
                $position = !empty($params['image_position']) && $params['image_position'] !== 'fill' ? $params['image_position'] : 'se';
                $process[] = "watermark,image_{$text},g_{$position},t_80";
            }
            $processStr = "image/" . implode('/', $process);
            $localFilename = sprintf('mask_%s_%s', microtime(true), $object);
            $localFilepath = storage_path("app/$savePath") . "/" . $localFilename;
            $options = [
                OssClient::OSS_PROCESS => $processStr,
                OssClient::OSS_FILE_DOWNLOAD => $localFilepath,
            ];
            \Log::info(sprintf('%s, process: %s', __METHOD__, $processStr));
            
            //处理并下载
            $ossClient->getObject($this->bucketName, $object, $options);
            //再上传远程
            $ossClient->uploadFile($this->bucketName, $localFilename, $localFilepath);
            $maskSignedUrl = $ossClient->signUrl($this->bucketName, $localFilename, 600);
            
            $params["original_image"] = $signedUrl;
            $params["mask_image"] = $maskSignedUrl;
            return back()->with([
                "success" => "处理完成",
                "original_image" => $signedUrl,
                "mask_image" => $maskSignedUrl,
            ])->withInput($params);
            
        }
        catch (\Exception $e)
        {
            dd($e);
        }
        
    }
    
    public function test()
    {
        dd(storage_path('image/oss'));
        
        
        try
        {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $object = 'tSG2bG7xkuTsrMFb.jpg';
//             $result = $ossClient->copyObject(
//                 $this->bucketName, 
//                 $object, 
//                 $this->bucketName, 
//                 "copy_" . microtime(true) . "_" . $object,
//                 [OssClient::OSS_PROCESS => 'image/watermark,type_d3F5LXplbmhlaQ==,text_NjY2,color_FF3366,g_nw,t_60,rotate_30,fill_1/watermark,image_NjcxOWFkNzNndzFldXlzZXRjOGU5ajIwYzgwZXJ3ZnkuanBnP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzA,g_se,t_60']
//             );

            $result = $ossClient->getObject($this->bucketName, $object,[
                OssClient::OSS_FILE_DOWNLOAD => storage_path('app/public/image/oss/xxx.jpg'),
                OssClient::OSS_PROCESS => "image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ"
            ]);
//             $r = file_put_contents('aaa.jpg', $result);
            dd($result);
        }
        catch (\Exception $e)
        {
            dd($e->getMessage());
        }
    }
}
